package com.cx.mall.demo.service;

import com.cx.mall.demo.utils.JwtUtils;
import com.cx.mall.demo.utils.ResponseMessageEnum;
import com.cx.mall.demo.utils.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 登录服务类
 */
@Service
public class LoginService {

    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 获取登录验证码
     */
    public boolean getLoginCode(String phoneNumber) {
        return verificationCodeService.sendCode(phoneNumber);
    }

    /**
     * 使用验证码登录
     */
    public LoginResult loginWithCode(String phoneNumber, String code) {
        if (verificationCodeService.verifyCode(phoneNumber, code)) {
            // 登录成功，生成token
            String token = generateToken(phoneNumber);
            return new LoginResult(true, ResponseMessageEnum.SUCCESS.getMessage(), token);
        } else {
            return new LoginResult(false, ResponseMessageEnum.CODE_ERROR_OR_EXPIRED.getMessage(), null);
        }
    }

    /**
     * 生成简单的登录令牌
     */
    private String generateToken(String phoneNumber) {
        //使用Jwt生成token
        Map<String,Object> map = new HashMap<>();
        map.put("phoneNumber",phoneNumber);
        String token = JwtUtils.generateToken(map);
        return token;
    }

    /**
     * 登录结果封装类
     */
    public static class LoginResult {
        private boolean success;
        private String message;
        private String token;

        public LoginResult(boolean success, String message, String token) {
            this.success = success;
            this.message = message;
            this.token = token;
        }

        // getter方法
        public boolean isSuccess() {
            return success;
        }

        public String getMessage() {
            return message;
        }

        public String getToken() {
            return token;
        }
    }
}

